import { tool } from "@langchain/core/tools";
import { z } from "zod";

export class AIToolsRegistry {
  constructor(private db: any, private currentUserId?: string) {}

  // 工具中文名称映射
  private toolNameMap: Record<string, string> = {
    'create_task': '创建任务',
    'query_tasks': '查询任务',
    'update_task': '更新任务',
    'delete_task': '删除任务',
    'complete_task': '完成任务',
    'set_reminder': '设置提醒',
    'get_kanban': '获取看板',
    'update_task_status': '更新任务状态',
    'move_task': '移动任务',
    'get_task_stats': '获取任务统计',
    'get_efficiency_metrics': '获取效率指标',
    'get_trend_analysis': '获取趋势分析',
    'get_notification_settings': '获取通知设置',
    'update_notification_settings': '更新通知设置',
    'generate_chart': '生成图表'
  };

  // 获取工具中文名称
  getToolChineseName(toolName: string): string {
    return this.toolNameMap[toolName] || toolName;
  }

  // 任务管理工具
  createTaskTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 创建任务工具被调用');
          
          const { title, description, priority, category, due_date, reminder } = input;
          
          const result = await this.db.query(`
            INSERT INTO tasks (user_id, title, description, priority, category, due_date, reminder, created_at, updated_at)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
            RETURNING *
          `, [
            this.currentUserId || 'anonymous',
            title,
            description || '',
            priority || 'medium',
            category || 'general',
            due_date ? new Date(due_date) : null,
            reminder || null,
            new Date(),
            new Date()
          ]);

          const response = {
            success: true,
            data: result.rows[0],
            message: `任务"${title}"创建成功`
          };

          console.log('[AI Tools] ✅ 任务创建成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 任务创建失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '任务创建失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "create_task",
        description: "创建新任务",
        schema: z.object({
          title: z.string().describe("任务标题"),
          description: z.string().optional().describe("任务描述"),
          priority: z.enum(['low', 'medium', 'high', 'urgent']).optional().describe("优先级"),
          category: z.string().optional().describe("任务分类"),
          due_date: z.string().optional().describe("截止日期，ISO格式"),
          reminder: z.string().optional().describe("提醒时间，ISO格式")
        })
      }
    );
  }

  queryTasksTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 查询任务工具被调用');
          
          const { status, priority, category, limit = 20, offset = 0 } = input;
          
          let whereClause = 'WHERE user_id = $1';
          const params: any[] = [this.currentUserId || 'anonymous'];
          let paramIndex = 2;

          if (status) {
            if (status === 'completed') {
              whereClause += ` AND completed = true`;
            } else if (status === 'pending') {
              whereClause += ` AND completed = false`;
            } else if (status === 'overdue') {
              const currentTime = new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
              }).replace(/\//g, '-')
              whereClause += ` AND completed = false AND due_date IS NOT NULL AND due_date::timestamp < $${paramIndex}`;
              params.push(currentTime);
              paramIndex++;
            }
          }

          if (priority) {
            whereClause += ` AND priority = $${paramIndex}`;
            params.push(priority);
            paramIndex++;
          }

          if (category) {
            whereClause += ` AND category = $${paramIndex}`;
            params.push(category);
            paramIndex++;
          }

          const result = await this.db.query(`
            SELECT * FROM tasks 
            ${whereClause}
            ORDER BY created_at DESC
            LIMIT $${paramIndex} OFFSET $${paramIndex + 1}
          `, [...params, limit, offset]);

          const response = {
            success: true,
            data: result.rows,
            message: `查询到 ${result.rows.length} 个任务`
          };

          console.log('[AI Tools] ✅ 任务查询成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 任务查询失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '任务查询失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "query_tasks",
        description: "查询任务列表",
        schema: z.object({
          status: z.enum(['all', 'completed', 'pending', 'overdue']).optional().describe("任务状态"),
          priority: z.enum(['low', 'medium', 'high', 'urgent']).optional().describe("优先级筛选"),
          category: z.string().optional().describe("分类筛选"),
          limit: z.number().optional().describe("返回数量限制"),
          offset: z.number().optional().describe("偏移量")
        })
      }
    );
  }

  updateTaskTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 更新任务工具被调用');
          
          const { task_id, title, description, priority, category, due_date, reminder, completed } = input;
          
          const result = await this.db.query(`
            UPDATE tasks 
            SET 
              title = COALESCE($1, title),
              description = COALESCE($2, description),
              priority = COALESCE($3, priority),
              category = COALESCE($4, category),
              due_date = COALESCE($5, due_date),
              reminder = COALESCE($6, reminder),
              completed = COALESCE($7, completed),
              updated_at = $8
            WHERE id = $9 AND user_id = $10
            RETURNING *
          `, [
            title, description, priority, category,
            due_date ? new Date(due_date) : null,
            reminder ? new Date(reminder) : null,
            completed, new Date(), task_id, this.currentUserId || 'anonymous'
          ]);

          if (result.rows.length === 0) {
            const errorResponse = {
              success: false,
              error: '任务不存在或无权限修改'
            };
            return JSON.stringify(errorResponse);
          }

          const response = {
            success: true,
            data: result.rows[0],
            message: `任务更新成功`
          };

          console.log('[AI Tools] ✅ 任务更新成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 任务更新失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '任务更新失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "update_task",
        description: "更新任务信息",
        schema: z.object({
          task_id: z.number().describe("任务ID"),
          title: z.string().optional().describe("任务标题"),
          description: z.string().optional().describe("任务描述"),
          priority: z.enum(['low', 'medium', 'high', 'urgent']).optional().describe("优先级"),
          category: z.string().optional().describe("任务分类"),
          due_date: z.string().optional().describe("截止日期，ISO格式"),
          reminder: z.string().optional().describe("提醒时间，ISO格式"),
          completed: z.boolean().optional().describe("是否完成")
        })
      }
    );
  }

  deleteTaskTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 删除任务工具被调用');
          
          const { task_id } = input;
          
          const result = await this.db.query(`
            DELETE FROM tasks 
            WHERE id = $1 AND user_id = $2
            RETURNING *
          `, [task_id, this.currentUserId || 'anonymous']);

          if (result.rows.length === 0) {
            const errorResponse = {
              success: false,
              error: '任务不存在或无权限删除'
            };
            return JSON.stringify(errorResponse);
          }

          const response = {
            success: true,
            data: result.rows[0],
            message: `任务删除成功`
          };

          console.log('[AI Tools] ✅ 任务删除成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 任务删除失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '任务删除失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "delete_task",
        description: "删除任务",
        schema: z.object({
          task_id: z.number().describe("任务ID")
        })
      }
    );
  }

  completeTaskTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 完成任务工具被调用');
          
          const { task_id } = input;
          
          const result = await this.db.query(`
            UPDATE tasks 
            SET completed = true, completed_at = $1, updated_at = $2
            WHERE id = $3 AND user_id = $4
            RETURNING *
          `, [new Date(), new Date(), task_id, this.currentUserId || 'anonymous']);

          if (result.rows.length === 0) {
            const errorResponse = {
              success: false,
              error: '任务不存在或无权限修改'
            };
            return JSON.stringify(errorResponse);
          }

          const response = {
            success: true,
            data: result.rows[0],
            message: `任务"${result.rows[0].title}"已完成`
          };

          console.log('[AI Tools] ✅ 任务完成成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 任务完成失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '任务完成失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "complete_task",
        description: "标记任务为完成",
        schema: z.object({
          task_id: z.number().describe("任务ID")
        })
      }
    );
  }

  setReminderTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 设置提醒工具被调用');
          
          const { task_id, reminder_time } = input;
          
          const result = await this.db.query(`
            UPDATE tasks 
            SET reminder = $1, updated_at = $2
            WHERE id = $3 AND user_id = $4
            RETURNING *
          `, [new Date(reminder_time), new Date(), task_id, this.currentUserId || 'anonymous']);

          if (result.rows.length === 0) {
            const errorResponse = {
              success: false,
              error: '任务不存在或无权限修改'
            };
            return JSON.stringify(errorResponse);
          }

          const response = {
            success: true,
            data: result.rows[0],
            message: `任务"${result.rows[0].title}"提醒设置成功`
          };

          console.log('[AI Tools] ✅ 提醒设置成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 提醒设置失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '提醒设置失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "set_reminder",
        description: "为任务设置提醒时间",
        schema: z.object({
          task_id: z.number().describe("任务ID"),
          reminder_time: z.string().describe("提醒时间，ISO格式")
        })
      }
    );
  }

  // 看板管理工具
  getKanbanTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 获取看板工具被调用');
          
          const result = await this.db.query(`
            SELECT 
              t.*,
              CASE 
                WHEN t.completed = true THEN 'completed'
                WHEN t.due_date IS NOT NULL AND t.due_date::timestamp < NOW() AND t.completed = false THEN 'overdue'
                WHEN t.priority = 'urgent' THEN 'urgent'
                WHEN t.priority = 'high' THEN 'high'
                WHEN t.priority = 'medium' THEN 'medium'
                ELSE 'low'
              END as status
            FROM tasks t
            WHERE t.user_id = $1
            ORDER BY 
              CASE 
                WHEN t.completed = true THEN 4
                WHEN t.due_date IS NOT NULL AND t.due_date::timestamp < NOW() AND t.completed = false THEN 1
                WHEN t.priority = 'urgent' THEN 2
                WHEN t.priority = 'high' THEN 3
                ELSE 5
              END,
              t.created_at DESC
          `, [this.currentUserId || 'anonymous']);

          const response = {
            success: true,
            data: result.rows,
            message: `看板数据获取成功，共 ${result.rows.length} 个任务`
          };

          console.log('[AI Tools] ✅ 看板数据获取成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 看板数据获取失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '看板数据获取失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "get_kanban",
        description: "获取看板视图数据",
        schema: z.object({})
      }
    );
  }

  updateTaskStatusTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 更新任务状态工具被调用');
          
          const { task_id, status } = input;
          
          let updateQuery = '';
          let params: any[] = [this.currentUserId || 'anonymous'];
          let paramIndex = 2;

          if (status === 'completed') {
            updateQuery = `UPDATE tasks SET completed = true, completed_at = $${paramIndex}, updated_at = $${paramIndex + 1} WHERE id = $${paramIndex + 2} AND user_id = $1 RETURNING *`;
            params.push(new Date(), new Date(), task_id);
          } else if (status === 'pending') {
            updateQuery = `UPDATE tasks SET completed = false, completed_at = NULL, updated_at = $${paramIndex} WHERE id = $${paramIndex + 1} AND user_id = $1 RETURNING *`;
            params.push(new Date(), task_id);
          } else {
            const errorResponse = {
              success: false,
              error: '无效的状态值，支持 completed 或 pending'
            };
            return JSON.stringify(errorResponse);
          }

          const result = await this.db.query(updateQuery, params);

          if (result.rows.length === 0) {
            const errorResponse = {
              success: false,
              error: '任务不存在或无权限修改'
            };
            return JSON.stringify(errorResponse);
          }

          const response = {
            success: true,
            data: result.rows[0],
            message: `任务状态更新为 ${status}`
          };

          console.log('[AI Tools] ✅ 任务状态更新成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 任务状态更新失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '任务状态更新失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "update_task_status",
        description: "更新任务状态",
        schema: z.object({
          task_id: z.number().describe("任务ID"),
          status: z.enum(['completed', 'pending']).describe("任务状态")
        })
      }
    );
  }

  moveTaskTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 移动任务工具被调用');
          
          const { task_id, new_priority, new_category } = input;
          
          const result = await this.db.query(`
            UPDATE tasks 
            SET 
              priority = COALESCE($1, priority),
              category = COALESCE($2, category),
              updated_at = $3
            WHERE id = $4 AND user_id = $5
            RETURNING *
          `, [new_priority, new_category, new Date(), task_id, this.currentUserId || 'anonymous']);

          if (result.rows.length === 0) {
            const errorResponse = {
              success: false,
              error: '任务不存在或无权限修改'
            };
            return JSON.stringify(errorResponse);
          }

          const response = {
            success: true,
            data: result.rows[0],
            message: `任务移动成功`
          };

          console.log('[AI Tools] ✅ 任务移动成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 任务移动失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '任务移动失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "move_task",
        description: "移动任务到不同优先级或分类",
        schema: z.object({
          task_id: z.number().describe("任务ID"),
          new_priority: z.enum(['low', 'medium', 'high', 'urgent']).optional().describe("新优先级"),
          new_category: z.string().optional().describe("新分类")
        })
      }
    );
  }

  // 统计工具
  getTaskStatsTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 获取任务统计工具被调用');
          
          // 基础统计
          const totalTasksResult = await this.db.query('SELECT COUNT(*) as count FROM tasks WHERE user_id = $1', [this.currentUserId || 'anonymous']);
          const completedTasksResult = await this.db.query('SELECT COUNT(*) as count FROM tasks WHERE completed = true AND user_id = $1', [this.currentUserId || 'anonymous']);
          const overdueTasksResult = await this.db.query(`
            SELECT COUNT(*) as count FROM tasks 
            WHERE completed = false 
              AND due_date IS NOT NULL 
              AND due_date::timestamp < NOW()
              AND user_id = $1
          `, [this.currentUserId || 'anonymous']);

          const totalTasks = parseInt(totalTasksResult.rows[0].count);
          const completedTasks = parseInt(completedTasksResult.rows[0].count);
          const overdueTasks = parseInt(overdueTasksResult.rows[0].count);
          const pendingTasks = totalTasks - completedTasks;
          
          const completionRate = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;
          const overdueRate = totalTasks > 0 ? Math.round((overdueTasks / totalTasks) * 100) : 0;

          const response = {
            success: true,
            data: {
              totalTasks,
              completedTasks,
              pendingTasks,
              overdueTasks,
              completionRate,
              overdueRate
            },
            message: `任务统计获取成功`
          };

          console.log('[AI Tools] ✅ 获取任务统计成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 获取任务统计失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '获取任务统计失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "get_task_stats",
        description: "获取任务统计概览",
        schema: z.object({})
      }
    );
  }

  getEfficiencyMetricsTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 获取效率指标工具被调用');
          
          // 获取最近7天的任务完成情况
          const weeklyStats = await this.db.query(`
            SELECT 
              DATE(created_at) as date,
              COUNT(*) as created,
              COUNT(CASE WHEN completed = true THEN 1 END) as completed
            FROM tasks 
            WHERE user_id = $1 
              AND created_at >= NOW() - INTERVAL '7 days'
            GROUP BY DATE(created_at)
            ORDER BY date DESC
          `, [this.currentUserId || 'anonymous']);

          // 获取优先级分布
          const priorityStats = await this.db.query(`
            SELECT priority, COUNT(*) as count
            FROM tasks 
            WHERE user_id = $1 AND completed = false
            GROUP BY priority
          `, [this.currentUserId || 'anonymous']);

          // 获取分类分布
          const categoryStats = await this.db.query(`
            SELECT category, COUNT(*) as count
            FROM tasks 
            WHERE user_id = $1 AND completed = false
            GROUP BY category
          `, [this.currentUserId || 'anonymous']);

          const response = {
            success: true,
            data: {
              weeklyStats: weeklyStats.rows,
              priorityDistribution: priorityStats.rows,
              categoryDistribution: categoryStats.rows
            },
            message: `效率指标获取成功`
          };

          console.log('[AI Tools] ✅ 获取效率指标成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 获取效率指标失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '获取效率指标失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "get_efficiency_metrics",
        description: "获取效率指标和趋势分析",
        schema: z.object({})
      }
    );
  }

  getTrendAnalysisTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 获取趋势分析工具被调用');
          
          const { days = 30 } = input;
          
          // 获取指定天数的趋势数据
          const trendData = await this.db.query(`
            SELECT 
              DATE(created_at) as date,
              COUNT(*) as created,
              COUNT(CASE WHEN completed = true THEN 1 END) as completed,
              COUNT(CASE WHEN completed = false AND due_date::timestamp < NOW() THEN 1 END) as overdue
            FROM tasks 
            WHERE user_id = $1 
              AND created_at >= NOW() - INTERVAL '${days} days'
            GROUP BY DATE(created_at)
            ORDER BY date ASC
          `, [this.currentUserId || 'anonymous']);

          const response = {
            success: true,
            data: {
              trendData: trendData.rows,
              period: `${days}天`
            },
            message: `趋势分析获取成功`
          };

          console.log('[AI Tools] ✅ 获取趋势分析成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 获取趋势分析失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '获取趋势分析失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "get_trend_analysis",
        description: "获取任务趋势分析",
        schema: z.object({
          days: z.number().optional().describe("分析天数，默认为30天")
        })
      }
    );
  }

  // 通知管理工具
  getNotificationSettingsTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 获取通知设置工具被调用');
          
          const result = await this.db.query(
            'SELECT * FROM notification_settings WHERE user_id = $1',
            [this.currentUserId || 'anonymous']
          );

          if (result.rows.length === 0) {
            // 返回默认设置
            const defaultSettings = {
              task_reminders: true,
              daily_summary: true,
              weekly_review: true,
              overdue_alerts: true,
              reminder_time: '09:00',
              sound_enabled: true,
              vibration_enabled: true,
              email_notifications: false
            };
            
            const response = {
              success: true,
              data: defaultSettings,
              message: `获取通知设置成功（默认设置）`
            };
            return JSON.stringify(response);
          }

          const response = {
            success: true,
            data: result.rows[0],
            message: `获取通知设置成功`
          };

          console.log('[AI Tools] ✅ 获取通知设置成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 获取通知设置失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '获取通知设置失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "get_notification_settings",
        description: "获取用户通知设置",
        schema: z.object({})
      }
    );
  }

  updateNotificationSettingsTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 更新通知设置工具被调用');
          
          const {
            task_reminders,
            daily_summary,
            weekly_review,
            overdue_alerts,
            reminder_time,
            sound_enabled,
            vibration_enabled,
            email_notifications
          } = input;

          // 检查是否已存在设置
          const existingSettings = await this.db.query(
            'SELECT id FROM notification_settings WHERE user_id = $1',
            [this.currentUserId || 'anonymous']
          );

          if (existingSettings.rows.length > 0) {
            // 更新现有设置
            const result = await this.db.query(`
              UPDATE notification_settings 
              SET 
                task_reminders = COALESCE($1, task_reminders),
                daily_summary = COALESCE($2, daily_summary),
                weekly_review = COALESCE($3, weekly_review),
                overdue_alerts = COALESCE($4, overdue_alerts),
                reminder_time = COALESCE($5, reminder_time),
                sound_enabled = COALESCE($6, sound_enabled),
                vibration_enabled = COALESCE($7, vibration_enabled),
                email_notifications = COALESCE($8, email_notifications),
                updated_at = $9
              WHERE user_id = $10
              RETURNING *
            `, [
              task_reminders, daily_summary, weekly_review, overdue_alerts,
              reminder_time, sound_enabled, vibration_enabled, email_notifications,
              new Date(), this.currentUserId || 'anonymous'
            ]);

            const response = {
              success: true,
              data: result.rows[0],
              message: `通知设置更新成功`
            };
            return JSON.stringify(response);
          } else {
            // 创建新设置
            const result = await this.db.query(`
              INSERT INTO notification_settings 
              (user_id, task_reminders, daily_summary, weekly_review, overdue_alerts, 
               reminder_time, sound_enabled, vibration_enabled, email_notifications)
              VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
              RETURNING *
            `, [
              this.currentUserId || 'anonymous',
              task_reminders ?? true,
              daily_summary ?? true,
              weekly_review ?? true,
              overdue_alerts ?? true,
              reminder_time ?? '09:00',
              sound_enabled ?? true,
              vibration_enabled ?? true,
              email_notifications ?? false
            ]);

            const response = {
              success: true,
              data: result.rows[0],
              message: `通知设置创建成功`
            };
            return JSON.stringify(response);
          }
        } catch (error) {
          console.error('[AI Tools] ❌ 更新通知设置失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '更新通知设置失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "update_notification_settings",
        description: "更新用户通知设置",
        schema: z.object({
          task_reminders: z.boolean().optional().describe("任务提醒"),
          daily_summary: z.boolean().optional().describe("每日总结"),
          weekly_review: z.boolean().optional().describe("每周回顾"),
          overdue_alerts: z.boolean().optional().describe("逾期提醒"),
          reminder_time: z.string().optional().describe("提醒时间，格式：HH:MM"),
          sound_enabled: z.boolean().optional().describe("声音提醒"),
          vibration_enabled: z.boolean().optional().describe("震动提醒"),
          email_notifications: z.boolean().optional().describe("邮件通知")
        })
      }
    );
  }

  // 生成图表工具
  generateChartTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[AI Tools] 🔍 生成图表工具被调用');
          
          const { chartType, title, description } = input;
          
          // 根据图表类型获取相应数据
          let chartData: any = {};
          
          switch (chartType) {
            case 'completion_rate':
              const statsResult = await this.db.query(`
                SELECT 
                  COUNT(*) as total,
                  COUNT(CASE WHEN completed = true THEN 1 END) as completed
                FROM tasks 
                WHERE user_id = $1
              `, [this.currentUserId || 'anonymous']);
              
              const stats = statsResult.rows[0];
              const completionRate = stats.total > 0 ? Math.round((stats.completed / stats.total) * 100) : 0;
              
              chartData = {
                type: 'chart',
                chartType: 'doughnut',
                title: title || '任务完成率',
                description: description || `总任务: ${stats.total}, 已完成: ${stats.completed}`,
                data: {
                  labels: ['已完成', '待完成'],
                  datasets: [{
                    data: [completionRate, 100 - completionRate],
                    backgroundColor: ['#22c55e', '#e2e8f0'],
                    borderColor: ['#16a34a', '#cbd5e1'],
                    borderWidth: 3
                  }]
                }
              };
              break;
              
            case 'priority_distribution':
              const priorityResult = await this.db.query(`
                SELECT priority, COUNT(*) as count
                FROM tasks 
                WHERE user_id = $1 AND completed = false
                GROUP BY priority
                ORDER BY 
                  CASE priority 
                    WHEN 'urgent' THEN 1
                    WHEN 'high' THEN 2
                    WHEN 'medium' THEN 3
                    WHEN 'low' THEN 4
                  END
              `, [this.currentUserId || 'anonymous']);
              
              chartData = {
                type: 'chart',
                chartType: 'bar',
                title: title || '任务优先级分布',
                description: description || '按优先级分类的待办任务数量',
                data: {
                  labels: priorityResult.rows.map((row: any) => {
                    const priorityMap: { [key: string]: string } = { urgent: '紧急', high: '高', medium: '中', low: '低' };
                    return priorityMap[row.priority] || row.priority;
                  }),
                  datasets: [{
                    label: '任务数量',
                    data: priorityResult.rows.map((row: any) => row.count),
                    backgroundColor: ['#ef4444', '#f97316', '#eab308', '#22c55e'],
                    borderColor: ['#dc2626', '#ea580c', '#ca8a04', '#16a34a'],
                    borderWidth: 2
                  }]
                }
              };
              break;
              
            case 'category_distribution':
              const categoryResult = await this.db.query(`
                SELECT category, COUNT(*) as count
                FROM tasks 
                WHERE user_id = $1 AND completed = false
                GROUP BY category
                ORDER BY count DESC
              `, [this.currentUserId || 'anonymous']);
              
              chartData = {
                type: 'chart',
                chartType: 'pie',
                title: title || '任务分类分布',
                description: description || '按分类统计的待办任务分布',
                data: {
                  labels: categoryResult.rows.map((row: any) => row.category),
                  datasets: [{
                    data: categoryResult.rows.map((row: any) => row.count),
                    backgroundColor: [
                      '#3b82f6', '#8b5cf6', '#06b6d4', '#10b981', 
                      '#f59e0b', '#ef4444', '#84cc16', '#f97316'
                    ],
                    borderColor: '#ffffff',
                    borderWidth: 2
                  }]
                }
              };
              break;
              
            case 'time_trends':
              const trendResult = await this.db.query(`
                SELECT 
                  DATE(created_at) as date,
                  COUNT(*) as created,
                  COUNT(CASE WHEN completed = true THEN 1 END) as completed
                FROM tasks 
                WHERE user_id = $1 
                  AND created_at >= NOW() - INTERVAL '7 days'
                GROUP BY DATE(created_at)
                ORDER BY date ASC
              `, [this.currentUserId || 'anonymous']);
              
              chartData = {
                type: 'chart',
                chartType: 'line',
                title: title || '任务趋势分析',
                description: description || '最近7天的任务创建和完成趋势',
                data: {
                  labels: trendResult.rows.map((row: any) => row.date),
                  datasets: [
                    {
                      label: '创建任务',
                      data: trendResult.rows.map((row: any) => row.created),
                      borderColor: '#3b82f6',
                      backgroundColor: 'rgba(59, 130, 246, 0.1)',
                      tension: 0.4
                    },
                    {
                      label: '完成任务',
                      data: trendResult.rows.map((row: any) => row.completed),
                      borderColor: '#22c55e',
                      backgroundColor: 'rgba(34, 197, 94, 0.1)',
                      tension: 0.4
                    }
                  ]
                }
              };
              break;
              
            default:
              throw new Error(`不支持的图表类型: ${chartType}`);
          }
          
          const response = {
            success: true,
            data: chartData,
            message: `图表生成成功: ${chartData.title}`
          };
          
          console.log('[AI Tools] ✅ 图表生成成功');
          return JSON.stringify(response);
        } catch (error) {
          console.error('[AI Tools] ❌ 图表生成失败:', error);
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '图表生成失败'
          };
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "generate_chart",
        description: "生成任务相关的图表",
        schema: z.object({
          chartType: z.enum(['completion_rate', 'priority_distribution', 'category_distribution', 'time_trends']).describe("图表类型"),
          title: z.string().optional().describe("图表标题"),
          description: z.string().optional().describe("图表描述")
        })
      }
    );
  }

  // 获取所有工具
  getAllTools() {
    return [
      // 任务管理工具
      this.createTaskTool(),
      this.queryTasksTool(),
      this.updateTaskTool(),
      this.deleteTaskTool(),
      this.completeTaskTool(),
      this.setReminderTool(),

      // 看板管理工具
      this.getKanbanTool(),
      this.updateTaskStatusTool(),
      this.moveTaskTool(),

      // 统计工具
      this.getTaskStatsTool(),
      this.getEfficiencyMetricsTool(),
      this.getTrendAnalysisTool(),

      // 通知管理工具
      this.getNotificationSettingsTool(),
      this.updateNotificationSettingsTool(),
      
      // 图表生成工具
      this.generateChartTool()
    ];
  }
}
